package _interview150;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 224. 基本计算器
 */
public class No224 {
    /**
     * 1. 模拟
     */
    public int calculate1(String s) {
        Deque<Integer> ops = new LinkedList<>();
        int sign = 1;
        ops.push(sign);

        int ans = 0;
        int n = s.length();
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == ' ') continue;
            else if (s.charAt(i) == '+') sign = ops.peek();
            else if (s.charAt(i) == '-') sign = -ops.peek();
            else if (s.charAt(i) == '(') ops.push(sign);
            else if (s.charAt(i) == ')') ops.pop();
            else {
                long num = 0;
                while (i < n && Character.isDigit(s.charAt(i))) {
                    num = num * 10 + s.charAt(i++) - '0';
                }
                i--;
                ans += sign * num;
            }
        }
        return ans;
    }

}
